package com.highspeed.bdk.service.security.user;

import com.bianmaba.spring.security.basic.configuration.BasicWebSecurityConfiguration;
import com.bianmaba.spring.security.details.UserDetailsServiceImpl;
import com.highspeed.bdk.bean.base.LocalUserDetails;
import com.highspeed.bdk.bean.entity.security.Role;
import com.highspeed.bdk.bean.entity.security.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CustomUserDetailsService extends UserDetailsServiceImpl {
    private static final Logger LOG = LoggerFactory.getLogger(CustomUserDetailsService.class);
    @Autowired
    private IUserService userService;

    public CustomUserDetailsService() {
        LOG.info("加载自定义UserDetailService：" + CustomUserDetailsService.class.getName());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (user != null) {
            List<SimpleGrantedAuthority> grantedAuthorities = createGrantedAuthorities(user.getRoles());
            UserDetails userDetails = new LocalUserDetails(user.getId(), user.getName(), user.getEmail(), user.getUsername(), user.getPassword(), user.getEnabled(),
                    user.getAccountExpiringDate().getTime() > System.currentTimeMillis(),
                    user.getCredentialsExpiringDate().getTime() > System.currentTimeMillis(),
                    !user.getLocked(), grantedAuthorities);
            return userDetails;
        }
        UserDetails userDetails = super.loadUserByUsername(username);
        return userDetails;
    }

    private List<SimpleGrantedAuthority> createGrantedAuthorities(List<Role> roles) {
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<SimpleGrantedAuthority>(0);
        for (Role role : roles) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        return grantedAuthorities;
    }
}
